/*
 *******************************************************************
 *
 * COPYRIGHT (coffee) 2013 - 2014 LTV Co., Ltd  All rights reserved
 *
 * Created  : Mar 9, 2014
 * Change History
 * =================================================================
 * DATE                DEVELOPER        REVISION      DESCRIPTION
 * =================================================================
 * Mar 9, 2014        Steven        1.0           First Created.
 * =================================================================
 *
 *
 *******************************************************************/
/**
 * 
 */
package vn.com.ltv.lo;

import java.util.ArrayList;
import java.util.HashMap;

import vn.com.ltv.lo.adapter.CommentAdapter;
import vn.com.ltv.lo.adapter.GViewAdapter;
import vn.com.ltv.lo.common.Constants;
import vn.com.ltv.lo.common.Decrypter;
import vn.com.ltv.lo.common.ImageDishObject;
import vn.com.ltv.lo.common.SessionManager;
import vn.com.ltv.lo.daos.CommentDAO;
import vn.com.ltv.lo.daos.DishDAO;
import vn.com.ltv.lo.daos.ImageDAO;
import vn.com.ltv.lo.daos.ImageDishDAO;
import vn.com.ltv.lo.daos.SetDAO;
import vn.com.ltv.lo.daos.SetListDAO;
import vn.com.ltv.lo.daos.UserDAO;
import vn.com.ltv.lo.dtos.CommentDTO;
import vn.com.ltv.lo.dtos.DishDTO;
import vn.com.ltv.lo.dtos.SetDTO;
import vn.com.ltv.lo.dtos.SetListDTO;
import vn.com.ltv.lo.dtos.UserDTO;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.three20.ui.TTImageView;

/**
 * @author Steven
 *
 */
@SuppressWarnings("deprecation")
public class DetailActivity extends Activity implements View.OnClickListener{
	
	//-----------Define variables---------------
	TextView tvTitle, tvCost, tvDescription;
	Button btnOrder,btnComment;
	TTImageView ivAvatar;
	RatingBar ratingBar;
	Gallery gallery;
	ListView lvComment;
	
	
	FrameLayout lnDialogComment;	
	TextView dialog_tvExit;
	EditText dialog_edtComment;
	Button dialog_btnComment;
	
	Bundle bundle;
	String extraId;
	int extraType;
	
//	ArrayList<SetDTO> listSet = new ArrayList<SetDTO>();
	ArrayList<DishDTO> listDish = new ArrayList<DishDTO>();
	ArrayList<ImageDishObject> listImage = new ArrayList<ImageDishObject>();	
	ArrayList<SetListDTO> listSetList = new ArrayList<SetListDTO>();
	ArrayList<CommentDTO> listComment = new ArrayList<CommentDTO>();
	SetDAO daoSet;
	DishDAO daoDish;
	ImageDishDAO daoImageDish;
	SetListDAO daoSetList;
	ImageDAO daoImage;
	
	CommentAdapter commentAdapter;
	Decrypter decrypter;
	
	SessionManager session;
	private String sEmail ="";
//	private String sFullName ="";
	
	
	// Hold a reference to the current animator,
    // so that it can be canceled mid-way.
    private Animator mCurrentAnimator;

    // The system "short" animation time duration, in milliseconds. This
    // duration is ideal for subtle animations or animations that occur
    // very frequently.
    private int mShortAnimationDuration;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail);
		try {
			Init();			
			loadData(extraType, extraId);			
						
			//-----------Actions---------------		
			btnOrder.setOnClickListener(this);
			btnComment.setOnClickListener(this);
			dialog_btnComment.setOnClickListener(this);
			dialog_tvExit.setOnClickListener(this);
			//-------------------------------------------------------------
			gallery.setAdapter(new GViewAdapter(this,listImage));      		
	        gallery.setOnItemClickListener(new OnItemClickListener() 
	        {
	            public void onItemClick(AdapterView<?> parent, 
	            View v, int position, long id) 
	            {             
	            	switch (extraType) {
					case Constants.EXTRA_VALUE_DISH:
						zoomImageFromThumb(v, listImage.get(position).getPath());
						break;
					case Constants.EXTRA_VALUE_SET:
						Intent intent = new Intent(DetailActivity.this,DetailActivity.class);
						intent.putExtra(Constants.EXTRA_ID, listImage.get(position).getDsh_id());
						intent.putExtra(Constants.EXTRA_TYPE, Constants.EXTRA_VALUE_DISH);
						startActivity(intent);
						break;
					default:
						break;
					}
	            	
	            }
	        });
	        //--------------------------------------------------------------------------------
	        
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
	}
	
	

	//-----------Initial variables---------------
	private void Init() throws Exception{
		tvTitle = (TextView)findViewById(R.id.detail_tvTitle);
		tvCost = (TextView)findViewById(R.id.detail_tvCost);
		tvDescription = (TextView)findViewById(R.id.detail_tvDescription);
		btnOrder = (Button)findViewById(R.id.detail_btnOrder);
		ivAvatar = (TTImageView)findViewById(R.id.detail_ivAvatar);
		ratingBar = (RatingBar)findViewById(R.id.detail_rbRating);
		gallery = (Gallery)findViewById(R.id.detail_gallery);
		btnComment = (Button)findViewById(R.id.detail_btnCreateCmt);
		lvComment =  (ListView)findViewById(R.id.detail_lvComment);
		lnDialogComment = (FrameLayout)findViewById(R.id.dialog_cmt);
		dialog_edtComment = (EditText)findViewById(R.id.dialog_cmt_tvMessage);
		dialog_btnComment = (Button)findViewById(R.id.dialog_cmt_btnComment);
		dialog_tvExit = (TextView)findViewById(R.id.dialog_tvExit);
		
		bundle = getIntent().getExtras();
		if (bundle.getString(Constants.EXTRA_ID)!= null) {
			extraId = bundle.getString(Constants.EXTRA_ID);
		}
		extraType = bundle.getInt(Constants.EXTRA_TYPE);
		
		
		session = new SessionManager(getApplicationContext());
		HashMap<String, String> user = session.getUserDetails(); 
//		sFullName = user.get(SessionManager.KEY_NAME);         
        sEmail = user.get(SessionManager.KEY_EMAIL);
        decrypter = new Decrypter();

	}
	
	//---------------------load data----------------------
	private void loadData(int extraType, String extraId) {
		
		
		daoImage = new ImageDAO(DetailActivity.this);		
		daoImageDish = new ImageDishDAO(DetailActivity.this);
		switch (extraType) {
		case Constants.EXTRA_VALUE_DISH:
			daoDish = new DishDAO(DetailActivity.this);			
			
			DishDTO dishDTO = new DishDTO();
			dishDTO = daoDish.get(extraId);
			//---------set data on layout------------
			tvTitle.setText(dishDTO.getDshNm());
			String sCostDish =String.format("%,d", dishDTO.getDshPrc());
			tvCost.setText(sCostDish.replaceAll(",", ".") +"VND");
			tvDescription.setText(dishDTO.getDshDesc());
			ivAvatar.setImageURL(dishDTO.getDshThumb());
			ratingBar.setRating(dishDTO.getDshRtAvrg());
			listImage.addAll(daoImageDish.getListImageByDishId(extraId));
			break;
			
		case Constants.EXTRA_VALUE_SET:
			daoSet = new SetDAO(DetailActivity.this);
			daoSetList = new SetListDAO(DetailActivity.this);
			SetDTO setDTO = new SetDTO();
			setDTO = daoSet.get(extraId);
			tvTitle.setText(setDTO.getSetNm());
			String sCostSet =String.format("%,d", setDTO.getSetPrc());
			tvCost.setText(sCostSet.replaceAll(",", ".") +"VND");
			tvDescription.setText(setDTO.getSetDesc());
			ivAvatar.setImageURL(daoImage.getPathImage(setDTO.getSetIdThumg()));
			ratingBar.setRating(setDTO.getSetRtAvrg());
			listImage.addAll(daoImageDish.getListImageBySetId(extraId));
			
			break;

		default:
			break;
		}	
		CommentDAO commentDAO = new CommentDAO(DetailActivity.this);			
		listComment = commentDAO.getListCommentByMenuId(extraId);
		commentAdapter = new CommentAdapter(DetailActivity.this, listComment);
		lvComment.setAdapter(commentAdapter);
		commentAdapter.notifyDataSetChanged();
		
	}

	
	
	//----------------  Action --------------------
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.detail_btnOrder :
				break;
		
			case R.id.detail_btnCreateCmt :
				dialog_edtComment.setText("");
				lnDialogComment.setVisibility(View.VISIBLE);
				break;
				
			case R.id.dialog_tvExit :			
				lnDialogComment.setVisibility(View.GONE);
				break;	
				
			case R.id.dialog_cmt_btnComment :			
				String sComment = dialog_edtComment.getText().toString();
				CommentDTO commentDTO = new CommentDTO();
				CommentDAO commentDAO = new CommentDAO(DetailActivity.this);
				UserDAO userDAO = new UserDAO(DetailActivity.this);					
				try {
					commentDTO.setUsrId(userDAO.get(decrypter.encrypt(sEmail)).getUsrId());
				} catch (Exception e) {
					e.printStackTrace();
				}
				commentDTO.setMnId(extraId);
				commentDTO.setCmtDesc(sComment);
				commentDAO.insert(commentDTO);
				
				listComment = commentDAO.getListCommentByMenuId(extraId);
				Log.d("listComment.size()", ""+listComment.size());
				commentAdapter = new CommentAdapter(DetailActivity.this, listComment);
				lvComment.setAdapter(commentAdapter);
				commentAdapter.notifyDataSetChanged();
				Toast.makeText(DetailActivity.this, "Comment is successful", Toast.LENGTH_SHORT).show();		
				lnDialogComment.setVisibility(View.GONE);						
				break;
			
			default:
				break;
		}
		
	}
	
	
	//--------------zoom image into center------------------
	private void zoomImageFromThumb(final View thumbView, String url) {
	    // If there's an animation in progress, cancel it
	    // immediately and proceed with this one.
	    if (mCurrentAnimator != null) {
	        mCurrentAnimator.cancel();
	    }

	    // Load the high-resolution "zoomed-in" image.
	    final TTImageView expandedImageView = (TTImageView) findViewById(
	            R.id.expanded_image);
	    expandedImageView.setImageURL(url);

	    // Calculate the starting and ending bounds for the zoomed-in image.
	    // This step involves lots of math. Yay, math.
	    final Rect startBounds = new Rect();
	    final Rect finalBounds = new Rect();
	    final Point globalOffset = new Point();

	    // The start bounds are the global visible rectangle of the thumbnail,
	    // and the final bounds are the global visible rectangle of the container
	    // view. Also set the container view's offset as the origin for the
	    // bounds, since that's the origin for the positioning animation
	    // properties (X, Y).
	    thumbView.getGlobalVisibleRect(startBounds);
	    findViewById(R.id.container)
	            .getGlobalVisibleRect(finalBounds, globalOffset);
	    startBounds.offset(-globalOffset.x, -globalOffset.y);
	    finalBounds.offset(-globalOffset.x, -globalOffset.y);

	    // Adjust the start bounds to be the same aspect ratio as the final
	    // bounds using the "center crop" technique. This prevents undesirable
	    // stretching during the animation. Also calculate the start scaling
	    // factor (the end scaling factor is always 1.0).
	    float startScale;
	    if ((float) finalBounds.width() / finalBounds.height()
	            > (float) startBounds.width() / startBounds.height()) {
	        // Extend start bounds horizontally
	        startScale = (float) startBounds.height() / finalBounds.height();
	        float startWidth = startScale * finalBounds.width();
	        float deltaWidth = (startWidth - startBounds.width()) / 2;
	        startBounds.left -= deltaWidth;
	        startBounds.right += deltaWidth;
	    } else {
	        // Extend start bounds vertically
	        startScale = (float) startBounds.width() / finalBounds.width();
	        float startHeight = startScale * finalBounds.height();
	        float deltaHeight = (startHeight - startBounds.height()) / 2;
	        startBounds.top -= deltaHeight;
	        startBounds.bottom += deltaHeight;
	    }

	    // Hide the thumbnail and show the zoomed-in view. When the animation
	    // begins, it will position the zoomed-in view in the place of the
	    // thumbnail.
	    thumbView.setAlpha(0f);
	    expandedImageView.setVisibility(View.VISIBLE);

	    // Set the pivot point for SCALE_X and SCALE_Y transformations
	    // to the top-left corner of the zoomed-in view (the default
	    // is the center of the view).
	    expandedImageView.setPivotX(0f);
	    expandedImageView.setPivotY(0f);

	    // Construct and run the parallel animation of the four translation and
	    // scale properties (X, Y, SCALE_X, and SCALE_Y).
	    AnimatorSet set = new AnimatorSet();
	    set
	            .play(ObjectAnimator.ofFloat(expandedImageView, View.X,
	                    startBounds.left, finalBounds.left))
	            .with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
	                    startBounds.top, finalBounds.top))
	            .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
	            startScale, 1f)).with(ObjectAnimator.ofFloat(expandedImageView,
	                    View.SCALE_Y, startScale, 1f));
	    set.setDuration(mShortAnimationDuration);
	    set.setInterpolator(new DecelerateInterpolator());
	    set.addListener(new AnimatorListenerAdapter() {
	        @Override
	        public void onAnimationEnd(Animator animation) {
	            mCurrentAnimator = null;
	        }

	        @Override
	        public void onAnimationCancel(Animator animation) {
	            mCurrentAnimator = null;
	        }
	    });
	    set.start();
	    mCurrentAnimator = set;

	    // Upon clicking the zoomed-in image, it should zoom back down
	    // to the original bounds and show the thumbnail instead of
	    // the expanded image.
	    final float startScaleFinal = startScale;
	    expandedImageView.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View view) {
	            if (mCurrentAnimator != null) {
	                mCurrentAnimator.cancel();
	            }

	            // Animate the four positioning/sizing properties in parallel,
	            // back to their original values.
	            AnimatorSet set = new AnimatorSet();
	            set.play(ObjectAnimator
	                        .ofFloat(expandedImageView, View.X, startBounds.left))
	                        .with(ObjectAnimator
	                                .ofFloat(expandedImageView, 
	                                        View.Y,startBounds.top))
	                        .with(ObjectAnimator
	                                .ofFloat(expandedImageView, 
	                                        View.SCALE_X, startScaleFinal))
	                        .with(ObjectAnimator
	                                .ofFloat(expandedImageView, 
	                                        View.SCALE_Y, startScaleFinal));
	            set.setDuration(mShortAnimationDuration);
	            set.setInterpolator(new DecelerateInterpolator());
	            set.addListener(new AnimatorListenerAdapter() {
	                @Override
	                public void onAnimationEnd(Animator animation) {
	                    thumbView.setAlpha(1f);
	                    expandedImageView.setVisibility(View.GONE);
	                    mCurrentAnimator = null;
	                }

	                @Override
	                public void onAnimationCancel(Animator animation) {
	                    thumbView.setAlpha(1f);
	                    expandedImageView.setVisibility(View.GONE);
	                    mCurrentAnimator = null;
	                }
	            });
	            set.start();
	            mCurrentAnimator = set;
	        }
	    });
	}
}
